class_name Tank extends Node3D

@onready var camera_3d = $Camera3D

@export var hull_type: TankGlobals.Hull = TankGlobals.Hull.WASP
@export var turret_type: TankGlobals.Turret = TankGlobals.Turret.SMOKY

# Hulls
var wasp = preload("res://Scenes/tank/hulls/Wasp.tscn")
var hunter = preload("res://Scenes/tank/hulls/Hunter.tscn")
# Turrets
var smoky = preload("res://Scenes/tank/turrets/Smoky.tscn")
var smoky_blue = preload("res://Scenes/tank/turrets/SmokyBlue.tscn")

var tank_hull: TankHull3D
var tank_turret: TankTurret3D

func _on_ready():
	set_multiplayer_authority(str(name).to_int())

func _ready():
	print(is_multiplayer_authority())
	match hull_type:
		TankGlobals.Hull.WASP:
			tank_hull = wasp.instantiate()
		TankGlobals.Hull.HUNTER:
			tank_hull = hunter.instantiate()
	add_child(tank_hull)
	
	match turret_type:
		TankGlobals.Turret.SMOKY:
			tank_turret = smoky.instantiate()
		TankGlobals.Turret.SMOKY_BLUE:
			tank_turret = smoky_blue.instantiate()
	tank_hull.add_child(tank_turret)
	
	var turret_pivot: Node3D = tank_hull.find_child('TurretPivot')
	if turret_pivot != null:
		tank_turret.position = turret_pivot.position
		tank_turret.rotation = Vector3(0, PI, 0)
	camera_3d.reparent(tank_turret)

func _process(delta):
	if not is_multiplayer_authority(): return
	camera_3d.current = true
	
	if Input.is_action_pressed("turret_left"):
		tank_turret.rotate_left(delta)
	if Input.is_action_pressed("turret_right"):
		tank_turret.rotate_right(delta)
	
	tank_hull.drive_direction = get_drive_direction()

func _unhandled_input(event):
	if not is_multiplayer_authority(): return
	if Input.is_action_just_pressed("fire"):
		tank_turret.fire()
		
func get_drive_direction() -> TankGlobals.DriveDirection:
	var direction: TankGlobals.DriveDirection = TankGlobals.DriveDirection.P
	if Input.is_action_pressed("move_forward"):
		direction = TankGlobals.DriveDirection.F
	if Input.is_action_pressed("move_backward"):
		direction = TankGlobals.DriveDirection.B
	if Input.is_action_pressed("turn_left"):
		match direction:
			TankGlobals.DriveDirection.F:
				direction = TankGlobals.DriveDirection.FL
			TankGlobals.DriveDirection.B:
				direction = TankGlobals.DriveDirection.BL
			_: 
				direction = TankGlobals.DriveDirection.L
	if Input.is_action_pressed("turn_right"):
		match direction:
			TankGlobals.DriveDirection.F:
				direction = TankGlobals.DriveDirection.FR
			TankGlobals.DriveDirection.B:
				direction = TankGlobals.DriveDirection.BR
			_: 
				direction = TankGlobals.DriveDirection.R
	return direction
